/**
 * 用户模块数据操作文件
 */

const { Op } = require('sequelize');
const { sequelize } = require('./common');
const { users } = sequelize.models;

/**
 * 添加
 * @param {*} user 
 */
const add = user => users.create(user);

/**
 * 修改
 * @param {*} user 
 * @returns 
 */
const update = user => users.update(user, { where: { id: user.id } });

/**
 * 修改状态
 * @param {*} id 
 * @param {*} status 
 * @returns 
 */
const changeStatus = ({ id, status }) => users.update({ status }, { where: { id } });

/**
 * 修改密码
 * @param {*} id 
 * @param {*} password 
 * @returns 
 */
const updatePassword = (id, password) => users.update({ password }, { where: { id } });

/**
 * 删除用户
 * @param {*} id 
 * @returns 
 */
const deleteUser = id => users.destroy({ where: { id } });

/**
 * 搜索
 * @param {*} param0 
 * @returns 
 */
const search = ({ pageNo, pageSize, role_id = 0, username = '', email = '', phone = '', status = 0 }) => users.findAndCountAll({
    limit: pageSize * 1,
    offset: pageSize * (pageNo - 1),
    order: ['id'],
    attributes: {
        exclude: ['password']
    },
    where: {
        ...(role_id * 1 ? { role_id } : {}),
        ...(status ? { status } : {}),
        ...(username ? {
            username: {
                [Op.like]: `%${username}%`
            }
        } : {}),
        ...(email ? {
            email: {
                [Op.like]: `%${email}%`
            }
        } : {}),
        ...(phone ? {
            phone: {
                [Op.like]: `%${phone}%`
            }
        } : {})
    }
});

const exists = (username, phone, id = 0) => users.findOne({
    attributes: ['username', 'phone'],
    where: {
        id: {
            [Op.not]: id
        },
        [Op.or]: {
            username,
            phone
        }
    }
});

/**
 * 根据用户名获取
 * @param {*} username 
 * @returns 
 */
const getUserByUsername = username => users.findOne({ where: { username } });

/**
 * 根据角色id查询用户是否存在
 * @param {*} role_id 
 * @returns 
 */
const existsByRoleId = role_id => users.findOne({ where: { role_id }, attributes: ['id'] });

module.exports = {
    add,
    update,
    search,
    exists,
    deleteUser,
    changeStatus,
    existsByRoleId,
    updatePassword,
    getUserByUsername
}